<template>
  <div class="device-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
     <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索设备名称"
        clearable
        style="width: 180px"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select
        v-model="searchStatus"
        placeholder="设备状态"
        clearable
        style="width: 140px"
      >
        <el-option label="启用" :value="1" />
        <el-option label="禁用" :value="0" />
      </el-select>

      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>重置
      </el-button>
      <el-button type="success" @click="openCreateDialog">
        <el-icon><Plus /></el-icon>新增
      </el-button>
    </div>
</div>
    <!-- 设备列表 -->
    <el-card shadow="never" class="device-list">
        <el-table
        v-loading="loading"
        :data="deviceList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="id" label="设备ID" width="80" />
        <el-table-column prop="name" label="设备名称" min-width="150" />
        <el-table-column prop="ownerName" label="设备主" min-width="120" />
        <el-table-column prop="location" label="位置" min-width="150" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="viewDeviceDetail(row)"
              >
                <el-icon><View /></el-icon>详情
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="openEditDialog(row)"
              >
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button
                :type="row.status === 1 ? 'danger' : 'success'"
                size="small"
                @click="toggleDeviceStatus(row)"
              >
                <el-icon><Switch /></el-icon>
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 设备表单 -->
    <el-dialog
  :title="dialogType === 'create' ? '添加设备' : '编辑设备'"
  v-model="dialogVisible"
  width="500px"
>
  <el-form
    ref="deviceFormRef"
    :model="deviceForm"
    :rules="deviceRules"
    label-width="100px"
  >
    <el-form-item label="设备名称" prop="name">
      <el-input v-model="deviceForm.name" placeholder="请输入设备名称" />
    </el-form-item>
    <el-form-item label="设备编号" prop="deviceCode">
      <el-input v-model="deviceForm.deviceCode" placeholder="请输入设备编号" />
    </el-form-item>
    <el-form-item label="设备类型" prop="type">
  <el-select v-model="deviceForm.type" placeholder="请选择设备类型" style="width: 100%">
    <el-option label="LCD屏幕" value="LCD_SCREEN" />
    <el-option label="LED显示屏" value="LED_DISPLAY" />
    <el-option label="数字标牌" value="DIGITAL_SIGNAGE" />
    <el-option label="触摸屏" value="TOUCH_SCREEN" />
    <el-option label="信息亭" value="INTERACTIVE_KIOSK" />
    <el-option label="其他" value="OTHER" />
  </el-select>
</el-form-item>
    <el-form-item label="设备位置" prop="location">
      <el-input v-model="deviceForm.location" placeholder="请输入设备位置" />
    </el-form-item>
    <el-form-item label="设备规格" prop="specifications">
      <el-input
        v-model="deviceForm.specifications"
        type="textarea"
        :rows="3"
        placeholder="请输入设备规格"
      />
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitDeviceForm">确定</el-button>
    </span>
  </template>
</el-dialog>

    <!-- 设备详情抽屉 -->
    <el-drawer
  v-model="drawerVisible"
  title="设备详情"
  size="50%"
  destroy-on-close
>
  <template v-if="currentDevice">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="设备ID" width="150px">
        {{ currentDevice.id }}
      </el-descriptions-item>
      <el-descriptions-item label="设备编号" width="150px">
        {{ currentDevice.deviceCode }}
      </el-descriptions-item>
      <el-descriptions-item label="设备名称">
        {{ currentDevice.name }}
      </el-descriptions-item>
      <el-descriptions-item label="设备类型">
        {{ getDeviceTypeName(currentDevice.type) }}
      </el-descriptions-item>
      <el-descriptions-item label="设备位置">
        {{ currentDevice.location }}
      </el-descriptions-item>
      <el-descriptions-item label="设备状态">
        <el-tag :type="currentDevice.status === 1 ? 'success' : 'danger'">
          {{ currentDevice.status === 1 ? '启用' : '禁用' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="设备规格" :span="2">
        {{ currentDevice.specifications || '暂无规格信息' }}
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ formatDateTime(currentDevice.createdTime) }}
      </el-descriptions-item>
      <el-descriptions-item label="更新时间">
        {{ formatDateTime(currentDevice.updatedTime) }}
      </el-descriptions-item>
    </el-descriptions>
  </template>
</el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDeviceList,
  getDeviceDetail,
  createDevice,
  updateDevice,
  deleteDevice,
  enableDevice,
  disableDevice,
  getDeviceStatistics,
  exportDeviceStatistics
} from '@/api/device'
import { userInfo } from '@/api/userControl'
import {
  Plus,
  Search,
  View,
  Edit,
  Delete,
  Switch,
  Refresh
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const loading = ref(false)
const deviceList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogType = ref('create')
const drawerVisible = ref(false)
const currentDevice = ref(null)
const searchStatus = ref(null)

// 设备类型映射
const deviceTypes = {
  'LCD_SCREEN': 'LCD屏幕',
  'LED_DISPLAY': 'LED显示屏',
  'DIGITAL_SIGNAGE': '数字标牌',
  'TOUCH_SCREEN': '触摸屏',
  'INTERACTIVE_KIOSK': '信息亭',
  'OTHER': '其他'
}

// 获取设备类型名称
const getDeviceTypeName = (type) => {
  return deviceTypes[type] || '未知类型'
}


// 表单相关
const deviceFormRef = ref(null)
const deviceForm = reactive({
  name: '',
  deviceCode: '',
  type: '',
  location: '',
  specifications: ''
})


// 表单验证规则
const deviceRules = {
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度应为2-50个字符', trigger: 'blur' }
  ],
  deviceCode: [
    { required: true, message: '请输入设备编号', trigger: 'blur' },
    { min: 2, max: 30, message: '长度应为2-30个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ],
  location: [
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  specifications: [
    { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  fetchDeviceList()
})
// 添加重置方法
const handleReset = () => {
  searchQuery.value = ''
  handleSearch()
}
// 获取设备列表
const fetchDeviceList = async () => {
  loading.value = true
  try {
    const res = await getDeviceList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchQuery.value, // 使用 name 作为搜索参数
      status: searchStatus.value // 添加状态筛选
    })
    if (res.data.code === 200) {
      const devices = res.data.data.records

      const ownerPromises = devices.map(device => 
        userInfo(device.ownerId)
          .then(userRes => {
            if (userRes.data.code === 200) {
              return {
                id: device.ownerId,
                username: userRes.data.data.username
              }
            }
            return {
              id: device.ownerId,
              username: '未知用户'
            }
          })
          .catch(() => ({
            id: device.ownerId,
            username: '未知用户'
          }))
      )
      
      const owners = await Promise.all(ownerPromises)
      
      deviceList.value = devices.map(device => ({
        ...device,
        ownerName: owners.find(owner => owner.id === device.ownerId)?.username || '未知用户'
      }))

      total.value = res.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

// 查看设备详情
// const viewDeviceDetail = async (device) => {
//   try {
//     const res = await getDeviceDetail(device.id)
//     if (res.data.code === 200) {
//       currentDevice.value = {
//         ...res.data.data,
//         ownerName: device.ownerName // 保留已获取的设备主名称
//       }
//       drawerVisible.value = true
//     }
//   } catch (error) {
//     ElMessage.error('获取设备详情失败')
//   }
// }

const viewDeviceDetail = (device) => {
  // adId.value = ads.id
  // currentAds.value = ads
  // drawerVisible.value = true
  router.push(`/admin/devices/${device.id}`)
}


// 打开创建对话框
const openCreateDialog = () => {
  dialogType.value = 'create'
  deviceForm.name = ''
  deviceForm.deviceCode = ''
  deviceForm.type = ''
  deviceForm.location = ''
  deviceForm.specifications = ''
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (device) => {
  dialogType.value = 'edit'
  try {
    loading.value = true
    const res = await getDeviceDetail(device.id)
    if (res.data.code === 200) {
      const deviceData = res.data.data
      // 使用获取到的详细数据填充表单
      deviceForm.id = deviceData.id
      deviceForm.name = deviceData.name
      deviceForm.deviceCode = deviceData.deviceCode
      deviceForm.type = deviceData.type
      deviceForm.location = deviceData.location
      deviceForm.specifications = deviceData.specifications
      dialogVisible.value = true
    } else {
      ElMessage.error(res.data.message || '获取设备详情失败')
    }
  } catch (error) {
    console.error('获取设备详情失败:', error)
    ElMessage.error('获取设备详情失败')
  } finally {
    loading.value = false
  }
}

// 修改提交设备表单方法
const submitDeviceForm = async () => {
  if (!deviceFormRef.value) return
  
  await deviceFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请正确填写表单信息')
      return
    }
    
    loading.value = true
    try {
      const submitData = {
        name: deviceForm.name,
        deviceCode: deviceForm.deviceCode,
        type: deviceForm.type,
        location: deviceForm.location,
        specifications: deviceForm.specifications
      }

      let response
      if (dialogType.value === 'create') {
        response = await createDevice(submitData)
      } else {
        response = await updateDevice(deviceForm.id, submitData)
      }
      
      const { data } = response
      
      if (data.code === 200) {
        ElMessage.success(dialogType.value === 'create' ? '创建成功' : '更新成功')
        dialogVisible.value = false
        fetchDeviceList()
      } else {
        ElMessage.error(data.message || (dialogType.value === 'create' ? '创建失败' : '更新失败'))
      }
    } catch (error) {
      console.error(dialogType.value === 'create' ? '创建设备失败:' : '更新设备失败:', error)
      ElMessage.error(error.response?.data?.message || '操作失败')
    } finally {
      loading.value = false
    }
  })
}


// 切换设备状态
const toggleDeviceStatus = async (device) => {
  try {
    if (device.status === 1) {
      await disableDevice(device.id)
      ElMessage.success('设备已禁用')
    } else {
      await enableDevice(device.id)
      ElMessage.success('设备已启用')
    }
    fetchDeviceList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除设备
const handleDelete = (device) => {
  ElMessageBox.confirm(
    '确定要删除该设备吗？此操作不可恢复',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteDevice(device.id)
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchDeviceList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchDeviceList()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchDeviceList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDeviceList()
}

// 格式化日期时间
// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未知'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 导出统计数据
const exportStatistics = async (deviceId) => {
  try {
    await getDeviceStatisticsExport(deviceId)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}
</script>

<style scoped>
.device-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 抽屉样式 */
:deep(.el-descriptions__label) {
  width: 150px;
  font-weight: bold;
}

:deep(.el-descriptions__content) {
  word-break: break-all;
}

:deep(.el-drawer__body) {
  padding: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-dropdown .el-icon--right) {
  margin-left: 4px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 5px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
  }

  .search-bar .el-input,
  .search-bar .el-select {
    width: 100% !important;
  }

  .search-bar .el-button {
    width: 100%;
  }
}
</style>